import XLSX from 'xlsx';

// 字符串转字符流
function s2ab(s) {
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
};

export default function downloadExl(column, data, info, type = 'xlsx') {
  const tempData = {};
  for (let index in column) {
    index = parseInt(index);
    tempData[`${XLSX.utils.encode_col(index)}1`] = { v: column[index].LABEL };
    for (const row in data) {
      tempData[`${XLSX.utils.encode_col(index)}${parseInt(row) + 2}`] = { v: data[row][column[index].CODE] || '' };
      if (column[index].TYPE === 'AMOUNT') {
        tempData[`${XLSX.utils.encode_col(index)}${parseInt(row) + 2}`] = {
          v: data[row][column[index].CODE] || '',
          t: 'n',
          z: '#,##0.00_ ',
        };
      }
    }
  }

  const outputPos = Object.keys(tempData);
  const tmpWB = {
    SheetNames: ['Sheet1'], // 保存的表标题
    Sheets: {
      Sheet1: Object.assign(
        {},
        tempData, // 内容
        {
          '!ref': `${outputPos[0]}:${outputPos[outputPos.length - 1]}`, // 设置填充区域
        }),
    },
  };
  const blob = s2ab(XLSX.write(tmpWB, { bookType: type, bookSST: false, type: 'binary' }));
  const tmpDown = new Blob([blob], { type: '' });
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(tmpDown, `${info.workbookName}.xlsx`);//filename文件名包括扩展名，下载路径为浏览器默认路径
  } else {
    const href = URL.createObjectURL(tmpDown); // 创建对象超链接
    const link = document.createElement('a');
    link.download = `${info.workbookName}.xlsx`;
    link.href = href;
    link.click();
  }
  setTimeout(() => {
    URL.revokeObjectURL(tmpDown);
  }, 100);
};